package com.hare.harelearn.DesignPattern;

public class 单例模式 {
    public static void main(String[] args) {
        SingletonEnum singleton = SingletonEnum.SINGLETON;
        singleton.icrement();
    }

}



/**
 * 饿汉式
 */
class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton(){
    }
    public static Singleton getSingleton(){
        return singleton;
    }
}



/**
 * 懒汉式及线程安全
 */
class SingletonLazy{
    private static SingletonLazy singletonLazy;

    private SingletonLazy(){

    }
    public static SingletonLazy getSingleton(){
        synchronized(SingletonLazy.class){
            if(singletonLazy == null){
                singletonLazy = new SingletonLazy();
            }
        }
        return singletonLazy;
    }
}

/**
 * 双重检索模式
 */
class SingletonLazyThreadSafe{
    private volatile static SingletonLazyThreadSafe singletonLazyThreadSafe;
    private SingletonLazyThreadSafe(){

    }
    public static SingletonLazyThreadSafe getSingleton(){
        if(singletonLazyThreadSafe == null) {
            synchronized (SingletonLazyThreadSafe.class) {
                if (singletonLazyThreadSafe == null) {
                    singletonLazyThreadSafe = new SingletonLazyThreadSafe();
                }
            }
        }
        return singletonLazyThreadSafe;
    }
}

/**
 * 静态内部类
 */
class SingletonStaticClass{
    public static class SingClass{
         public static final SingletonStaticClass str = new SingletonStaticClass();
    }

    private SingletonStaticClass(){}

    public static final SingletonStaticClass getInstance(){
        return SingClass.str;
    }
}

enum SingletonEnum{
    SINGLETON;

    private int count;

    public void icrement(){
        count++;
    }
}
